const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const rp = require('request-promise')

rp({
  uri:'http://127.0.0.1:3001/tag',
  json: true
}).then(res => {
  const tagMap = {}
  res.data.forEach((t) => tagMap[t.name]=t)
  buildApp({tagMap})
})

function requestBlog(blogHref) {
  return rp({
          uri:`http://127.0.0.1:3001/blog/href/${blogHref}`,
          json: true
        })
}

function renderPage({req, res, tagName, tagId, blogName, blogId, page}) {
  app.render(req, res, '/', {
    tag: tagId,
    tagName,
    blog: blogId,
    blogName,
    page
  })
}

function buildApp({tagMap}){
  app.prepare()
  .then(() => {
    const server = express()

    server.get('/tag/:tagName/:blogHref?', (req, res) => {
      const tag = req.params.tagName
      const blog = req.params.blogHref
      const page = req.query.page
      if(blog) {
        requestBlog(blog).then(resolve => {
          renderPage({
            req, res,
            tagName: tagMap[tag] ? tag :'',
            tagId: tagMap[tag]._id,
            blogName: blog,
            blogId: resolve.data._id,
            page
          })
        }, reject => {
          renderPage({
            tagName: tagMap[tag] ? tag :'',
            tagId: tagMap[tag]._id,
            page
          })
        }) 
      } else {
        renderPage({
          req, res,
          tagName: tagMap[tag] ? tag :'',
          tagId: tagMap[tag]._id,
          page
        })
      }
 
    })

    server.get('/:blogHref', (req, res) => {
      const page = req.query.page      
      requestBlog(req.params.blogHref).then(resolve => {
        renderPage({
          req, res,
          blogId: resolve.data._id,
          blogName: req.params.blogHref,
          page
        })
      }, reject => {
        renderPage({req, res, page})
      })
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(3000, (err) => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch((ex) => {
    console.error(ex.stack)
    process.exit(1)
  })
}